﻿using I_Ear_Tag.Demoin.EarTagManagement;
using I_Ear_Tag.Infrastructure.Interface;
using I_Ear_Tag.Read.Api.Application.Command.EarTagCommand;
using MediatR;

namespace I_Ear_Tag.Read.Api.Application.CommandHandlers.EarTagHandler
{
    public class MarkShowCommandHandler : IRequestHandler<MarkShowCommand, Page<Mark>>
    {
        private readonly IMarkRepository markRepository;
        public MarkShowCommandHandler(IMarkRepository markRepository)
        {
            this.markRepository = markRepository;
        }
        /// <summary>
        /// 显示羊只戴标信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Page<Mark>> Handle(MarkShowCommand request, CancellationToken cancellationToken)
        {
            var list = await markRepository.GetAsync(x => x.IsDel == true);
            if (!string.IsNullOrEmpty(request.EarNumber))
            {
                list = await markRepository.GetAsync(x => x.EarNumber.Contains(request.EarNumber) && !x.IsDel == false);
            }
            if (!string.IsNullOrEmpty(request.OldEarTag))
            {
                list = await markRepository.GetAsync(x => x.OldEarTag.Contains(request.OldEarTag) && !x.IsDel == false);
            }
            if (!string.IsNullOrEmpty(request.NewEarTag))
            {
                list = await markRepository.GetAsync(x => x.NewEarTag.Contains(request.NewEarTag) && !x.IsDel == false);
            }
            if (request.Reason != null)
            {
                list = await markRepository.GetAsync(x => x.Reason == request.Reason && !x.IsDel == false);
            }
            int total = list.Count();
            int pageCount =(int)Math.Ceiling( (total * 1.0) / request.pageSize);
            list = list.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            return new Page<Mark>
            {
                total = total,
                pageCount = pageCount,
                Data = list
            };

        }
    }
}
